<template>
  <div class="app-container">
    <!-- 移除搜索栏 -->

    <!-- 楼层标签页（简洁样式） -->
    <el-tabs 
      v-model="activeFloor" 
      @tab-click="handleFloorChange"
      style="margin: 10px 0;"
    >
      <el-tab-pane 
        v-for="floor in floorList" 
        :key="floor.floorId" 
        :label="floor.floorName" 
        :name="floor.floorId.toString()"
      >
        <!-- 房间列表 -->
        <div class="room-list">
          <div 
            v-for="room in currentRoomList" 
            :key="room.roomId" 
            class="room-card"
          >
            <div class="room-header">
              <span>房间号：{{ room.roomNo }}</span>
              <el-button 
                size="mini" 
                type="primary" 
                @click="openBatchBindDialog(room.roomId)"
              >
                批量设置护理员
              </el-button>
            </div>
            <!-- 床位列表（一行多列布局） -->
            <div class="bed-list">
              <div 
                v-for="bed in room.beds" 
                :key="bed.bedId" 
                class="bed-card"
              >
                <div>床位号：{{ bed.bedNo }}</div>
                <div>老人姓名：{{ bed.elderlyName || '无' }}</div>
                <div>护理员姓名：
                  <template v-if="bed.caregivers && bed.caregivers.length">
                    <el-tag 
                      v-for="cg in bed.caregivers" 
                      :key="cg.userId" 
                      closable
                      @close="handleRemoveCaregiver(bed, cg.userId)"
                    >
                      {{ cg.userName }}
                    </el-tag>
                  </template>
                  <template v-else>当前床位没有安排护理员</template>
                </div>
                <el-button 
                  size="mini" 
                  type="text" 
                  @click="openBindDialog(bed)"
                  :disabled="bed.caregivers && bed.caregivers.length >= 4"
                >
                  {{ bed.caregivers && bed.caregivers.length >= 4 ? '已满员' : '设置护理员' }}
                </el-button>
              </div>
            </div>
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>

    <!-- 护理员绑定弹窗（多选下拉+标签） -->
    <el-dialog 
      :title="currentBed?.type === 'room' ? '批量绑定护理员' : '设置护理员'" 
      v-model="bindDialogVisible" 
      width="400px"
    >
      <el-form :model="bindForm" label-width="80px">
        <el-form-item label="护理员姓名" required>
          <el-select 
            v-model="bindForm.caregiverIds" 
            multiple 
            collapse-tags 
            placeholder="请选择护理员"
          >
            <el-option 
              v-for="cg in allCaregivers" 
              :key="cg.userId" 
              :label="getCaregiverLabel(cg)"
              :value="cg.userId"
              :disabled="isCaregiverDisabled(cg.userId)"
            />
          </el-select>
          <div v-if="bindForm.caregiverIds.length >= 4" style="color: #f56c6c; font-size: 12px; margin-top: 5px;">
            已达上限（4个），如需更换请先取消现有护理员
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="bindDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmBind" :disabled="bindForm.caregiverIds.length > 4">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue'
import request from '@/utils/request'
import { ElMessage } from 'element-plus'

// 响应式数据（移除searchKey相关）
const floorList = ref([])
const activeFloor = ref('')
const currentRoomList = ref([])
const allCaregivers = ref([])
const boundCaregiverIds = ref([]) // 已被绑定的护理员ID列表
const bindDialogVisible = ref(false)
const currentBed = ref(null)
const bindForm = reactive({ caregiverIds: [] })

// 页面加载时查询数据（无需搜索参数）
onMounted(() => {
  handleQuery()
})

// 查询床位数据（移除搜索参数）
const handleQuery = () => {
  request.get('/bed/bed/listDto').then(res => {  // 不再传递searchKey参数
    if (res.code === 200) {
      formatFloorRoomData(res.rows)
      console.log(res);
       
    } else {
      ElMessage.error('查询失败：' + (res.msg || '未知错误'))
    }
  }).catch(err => {
    console.error('接口异常：', err)
    ElMessage.error('网络错误，请重试')
  })
}

// 格式化楼层-房间-床位层级数据（不变）
const formatFloorRoomData = (bedList) => {
  const floorMap = {}
  bedList.forEach(bed => {
    const floorId = bed.floorId
    if (!floorMap[floorId]) {
      floorMap[floorId] = {
        floorId: bed.floorId,
        floorName: bed.floorName,
        rooms: {}
      }
    }
    const roomId = bed.roomId
    if (!floorMap[floorId].rooms[roomId]) {
      floorMap[floorId].rooms[roomId] = {
        roomId: bed.roomId,
        roomNo: bed.roomNo,
        roomType: bed.roomType,
        totalBeds: bed.totalBeds,
        occupiedBeds: bed.occupiedBeds,
        beds: []
      }
    }
    floorMap[floorId].rooms[roomId].beds.push(bed)
  })
  floorList.value = Object.values(floorMap)
  if (floorList.value.length) {
    activeFloor.value = floorList.value[0].floorId.toString()
    handleFloorChange()
  }
}

// 切换楼层时更新房间列表（不变）
const handleFloorChange = () => {
  const currentFloor = floorList.value.find(f => f.floorId.toString() === activeFloor.value)
  currentRoomList.value = currentFloor ? Object.values(currentFloor.rooms) : []
}

// 打开单个床位绑定弹窗（不变）
const openBindDialog = (bed) => {
  currentBed.value = { ...bed, type: 'bed' }
  bindDialogVisible.value = true
  loadCaregivers()
  bindForm.caregiverIds = (bed.caregivers?.map(cg => cg.userId) || []).slice(0, 4)
}

// 打开房间批量绑定弹窗（不变）
const openBatchBindDialog = (roomId) => {
  currentBed.value = { roomId, type: 'room' }
  bindDialogVisible.value = true
  loadCaregivers()
  bindForm.caregiverIds = []
}

// 加载护理员列表
const loadCaregivers = () => {
  // 同时获取所有护理员和已被绑定的护理员ID列表
  Promise.all([
    request.get('/system/user/list', {
      params: { 
        status: '0',          // 启用状态
        roleKey: 'caregiver', // 护理员角色
        pageNum: 1,           // 第1页
        pageSize: 1000        // 每页1000条，确保获取所有护理员
      }
    }),
    request.get('/bed/bed/bound-caregivers')
  ]).then(([caregiversRes, boundRes]) => {
    if (caregiversRes.code === 200) {
      allCaregivers.value = caregiversRes.rows.map(user => ({
        userId: user.userId,
        userName: user.userName
      }))
      console.log(`加载护理员成功，共 ${allCaregivers.value.length} 人`)
    } else {
      ElMessage.error('加载护理员失败：' + caregiversRes.msg)
    }
    
    if (boundRes.code === 200) {
      boundCaregiverIds.value = boundRes.data || []
      console.log(`已绑定护理员数量：${boundCaregiverIds.value.length}`)
    }
  }).catch(err => {
    console.error('加载数据失败：', err)
    ElMessage.error('加载数据失败，请重试')
  })
}

// 确认绑定护理员（不变）
const confirmBind = () => {
  if (!currentBed.value) return
  if (bindForm.caregiverIds.length > 4) {
    ElMessage.warning('最多只能选择4个护理员')
    return
  }
  let url = ''
  if (currentBed.value.type === 'bed') {
    url = `/bed/bed/${currentBed.value.bedId}/caregivers`
  } else if (currentBed.value.type === 'room') {
    url = `/bed/bed/room/${currentBed.value.roomId}/caregivers`
  }
  request.post(url, bindForm.caregiverIds).then(res => {
    if (res.code === 200) {
      ElMessage.success('绑定成功')
      bindDialogVisible.value = false
      handleQuery()
    } else {
      ElMessage.error('绑定失败：' + res.msg)
    }
  })
}

// 快速删除单个护理员（点击标签的 × 按钮）
const handleRemoveCaregiver = (bed, caregiverIdToRemove) => {
  // 获取当前床位的所有护理员ID
  const currentCaregiversIds = (bed.caregivers || []).map(cg => cg.userId)
  // 移除指定的护理员ID
  const updatedCaregiversIds = currentCaregiversIds.filter(id => id !== caregiverIdToRemove)
  
  // 调用后端接口更新
  const url = `/bed/bed/${bed.bedId}/caregivers`
  request.post(url, updatedCaregiversIds).then(res => {
    if (res.code === 200) {
      ElMessage.success('取消绑定成功')
      handleQuery()
    } else {
      ElMessage.error('取消绑定失败：' + res.msg)
    }
  })
}

// 判断护理员是否应该被禁用
const isCaregiverDisabled = (caregiverId) => {
  // 当前床位已绑定的护理员
  const currentBedCaregiverIds = currentBed.value?.caregivers?.map(cg => cg.userId) || []
  
  // 如果是当前床位已绑定的护理员，不禁用
  if (currentBedCaregiverIds.includes(caregiverId)) {
    return false
  }
  
  // 如果该护理员已被其他床位绑定，禁用
  if (boundCaregiverIds.value.includes(caregiverId)) {
    return true
  }
  
  // 如果已选择4个护理员，且当前护理员未被选中，禁用
  if (bindForm.caregiverIds.length >= 4 && !bindForm.caregiverIds.includes(caregiverId)) {
    return true
  }
  
  return false
}

// 获取护理员显示标签（如果已被绑定，添加提示）
const getCaregiverLabel = (caregiver) => {
  const currentBedCaregiverIds = currentBed.value?.caregivers?.map(cg => cg.userId) || []
  
  // 如果是当前床位已绑定的，正常显示
  if (currentBedCaregiverIds.includes(caregiver.userId)) {
    return caregiver.userName
  }
  
  // 如果被其他床位绑定，添加标识
  if (boundCaregiverIds.value.includes(caregiver.userId)) {
    return `${caregiver.userName} (已被其他床位绑定)`
  }
  
  return caregiver.userName
}
</script>

<style scoped>
/* 页面容器浅灰背景 */
.app-container {
  background-color: #f5f7fa;
  padding: 20px;
  min-height: calc(100vh - 84px);
}

/* 楼层标签页样式优化 */
:deep(.el-tabs__header) {
  margin: 0 0 20px 0;
  background-color: #fff;
  padding: 0 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

:deep(.el-tabs__item) {
  font-size: 15px;
  font-weight: 500;
  color: #606266;
  padding: 0 30px;
  height: 48px;
  line-height: 48px;
}

:deep(.el-tabs__item.is-active) {
  color: #00B290;
  font-weight: 600;
}

:deep(.el-tabs__active-bar) {
  background-color: #00B290;
  height: 3px;
}

/* 房间卡片样式（增强阴影和圆角） */
.room-card {
  background-color: #fff;
  border: none;
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
}

.room-card:hover {
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12);
  transform: translateY(-2px);
}

.room-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 2px solid #f0f2f5;
}

.room-header > span {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  letter-spacing: 0.5px;
}

/* 床位列表布局 */
.bed-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 16px;
}

/* 床位卡片样式（优化视觉效果） */
.bed-card {
  background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
  border: 1px solid #e4e7ed;
  border-radius: 10px;
  padding: 16px;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
}

.bed-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 4px;
  height: 100%;
  background: linear-gradient(180deg, #00B290 0%, #089d82 100%);
  transform: scaleY(0);
  transition: transform 0.3s ease;
}

.bed-card:hover {
  border-color: #00B290;
  box-shadow: 0 4px 12px rgba(0, 178, 144, 0.15);
  transform: translateY(-2px);
}

.bed-card:hover::before {
  transform: scaleY(1);
}

.bed-card > div {
  margin-bottom: 10px;
  font-size: 14px;
  color: #606266;
  line-height: 1.6;
}

.bed-card > div:first-child {
  font-weight: 600;
  color: #303133;
  font-size: 15px;
  margin-bottom: 12px;
}

.bed-card > div:nth-child(2) {
  color: #409eff;
  font-weight: 500;
}

.bed-card > div:nth-child(3) {
  min-height: 40px;
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 8px;
}

/* 护理员标签美化 */
:deep(.el-tag) {
  background: linear-gradient(135deg, #00B290 0%, #089d82 100%);
  color: #fff;
  border: none;
  padding: 6px 14px;
  border-radius: 20px;
  font-size: 13px;
  font-weight: 500;
  transition: all 0.3s ease;
  box-shadow: 0 2px 6px rgba(0, 178, 144, 0.2);
}

:deep(.el-tag):hover {
  transform: translateY(-1px);
  box-shadow: 0 3px 8px rgba(0, 178, 144, 0.3);
}

:deep(.el-tag .el-icon-close) {
  color: #fff;
}

:deep(.el-tag .el-icon-close:hover) {
  background-color: rgba(255, 255, 255, 0.3);
  border-radius: 50%;
}

/* 设置护理员按钮优化 */
.bed-card .el-button--text {
  color: #00B290;
  font-weight: 500;
  margin-top: 8px;
  padding: 6px 0;
  transition: all 0.3s ease;
}

.bed-card .el-button--text:hover {
  color: #089d82;
  transform: translateX(3px);
}

.bed-card .el-button--text.is-disabled {
  color: #c0c4cc;
  cursor: not-allowed;
}

/* 批量设置护理员按钮 */
.room-header .el-button--primary {
  background: linear-gradient(135deg, #00B290 0%, #089d82 100%);
  border: none;
  border-radius: 20px;
  padding: 8px 20px;
  font-weight: 500;
  box-shadow: 0 2px 8px rgba(0, 178, 144, 0.3);
  transition: all 0.3s ease;
}

.room-header .el-button--primary:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 178, 144, 0.4);
}

/* 空状态提示 */
.bed-card > div:nth-child(3)::before {
  content: '👤';
  margin-right: 6px;
}

/* 对话框优化 */
:deep(.el-dialog) {
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.12);
}

:deep(.el-dialog__header) {
  background: linear-gradient(135deg, #00B290 0%, #089d82 100%);
  padding: 20px;
  border-radius: 12px 12px 0 0;
}

:deep(.el-dialog__title) {
  color: #fff;
  font-weight: 600;
  font-size: 16px;
}

:deep(.el-dialog__close) {
  color: #fff;
}

:deep(.el-dialog__body) {
  padding: 24px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #606266;
}

:deep(.el-select) {
  width: 100%;
}

:deep(.el-dialog__footer) {
  padding: 16px 24px;
  border-top: 1px solid #e4e7ed;
}

/* 提示文字样式 */
.el-form-item > div[style*="color: #f56c6c"] {
  background-color: #fef0f0;
  padding: 8px 12px;
  border-radius: 6px;
  border-left: 3px solid #f56c6c;
}

/* 无数据状态 */
.bed-card > div:last-child {
  color: #909399;
  font-style: italic;
}

/* 响应式优化 */
@media (max-width: 1400px) {
  .bed-list {
    grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  }
}

@media (max-width: 768px) {
  .bed-list {
    grid-template-columns: 1fr;
  }
  
  .room-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
  
  .room-header .el-button {
    width: 100%;
  }
}
</style>